package weilus.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import weilus.Coffee;
import weilus.CoffeeList;

import java.time.Duration;
import java.util.Arrays;


@RestController
@RequestMapping("/redis")
public class TestController {

    @Autowired
    ReactiveRedisOperations<String, Coffee> coffeeOps;

    @Value("classpath:redis-list.lua")
    private Resource redisListLua;

    @GetMapping("coffee")
    public Mono<CoffeeList> coffee(){
        return Mono.just(new CoffeeList(coffeeOps.keys("*").flatMap(coffeeOps.opsForValue()::get)));
    }

    @PostMapping("coffee")
    public Mono<Boolean> cache(@RequestBody Coffee coffee){
        return coffeeOps.opsForValue().set(coffee.getName(),coffee, Duration.ofMinutes(60));
    }

    @GetMapping("lua")
    public Flux test(){
        return coffeeOps.execute(RedisScript.of(redisListLua),
                Arrays.asList(
                        "live:room:find",
                        "live:room:base",
                        "live:room:count:",
                        "live:room:shop:"),
                Arrays.asList(0,19));
    }

}
